﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Dashboard.ProductBonus.Business;
using Infragistics.Win;
using Infragistics.Win.UltraWinGrid;

namespace Dashboard.ProductBonus
{
    public partial class FormUnproductiveTimeAdd : Form
    {
        private ValueList _valueListReason = new ValueList();

        public FormUnproductiveTimeAdd()
        {
            InitializeComponent();
        }

        private void toolStripButtonCreate_Click(object sender, EventArgs e)
        {
            // 重新刷新Grid
            this.BindGrid();
        }

        private void toolStripButtonSave_Click(object sender, EventArgs e)
        {
            try
            {
                this.ultraGridMain.UpdateData();
                this.Cursor = Cursors.WaitCursor;

                string reasonCode = string.Empty;
                string reasonName = string.Empty;
                int totalTime = 0;
                string staffNo = string.Empty;
                DateTime date;
                string fromTime = null;
                string toTime = null;

                List<string> sqlList = new List<string>();

                UnproductiveTime ut = new UnproductiveTime();

                foreach (UltraGridRow row in this.ultraGridMain.Rows)
                {
                    // 如果没有选择ReasonCode且没有输入TotalTime（或TotalTime=0）,则改行不保存
                    reasonCode = Convert.ToString(row.Cells["Reason"].Value);
                    reasonName = row.Cells["Reason"].Text;
                    totalTime = row.Cells["TotalTime"].Value == null ? 0 : int.Parse(row.Cells["TotalTime"].Value.ToString());

                    if (string.IsNullOrEmpty(reasonCode) && totalTime == 0)
                    {
                        continue;
                    }

                    if (totalTime > 0 && string.IsNullOrEmpty(reasonCode))
                    {
                        row.Selected = true;
                        row.Cells["Reason"].Selected = true;
                        MessageBox.Show(this, "Please select a reason.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }

                    if (totalTime == 0 && !string.IsNullOrEmpty(reasonCode))
                    {
                        row.Selected = true;
                        row.Cells["TotalTime"].Selected = true;
                        MessageBox.Show(this, "Please entry the total hour.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }

                    staffNo = row.Cells["StaffNo"].Value.ToString();
                    date = Convert.ToDateTime(row.Cells["Date"].Value);
                    fromTime = string.IsNullOrEmpty(Convert.ToString(row.Cells["FromTime"].Value)) ? "null" : "'" + this.ConvertToDateTime(row.Cells["FromTime"].Text).ToString("HH:mm") + "'";
                    toTime = string.IsNullOrEmpty(Convert.ToString(row.Cells["ToTime"].Value)) ? "null" : "'" + this.ConvertToDateTime(row.Cells["ToTime"].Text).ToString("HH:mm") + "'";

                    // 判断是否同一个ReasonCode+同一个用户+同一天已经存在记录，如果有，则不可再次保存
                    if (ut.ExistUnproductiveTime(staffNo, date, reasonCode))
                    {
                        MessageBox.Show(this, string.Format("There is already an " + reasonName + " record of the date [{0}] for this staff [{1}].", date.ToString("yyyy-MM-dd"), staffNo), "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        row.Selected = true;
                        return;
                    }

                    sqlList.Add(string.Format(@"
    INSERT INTO AbnormalWorkingTime
           (StaffNo
           ,TimeType
           ,ReasonCode
           ,Date
           ,FromTime
           ,ToTime
           ,TotalTime
           ,InsertBy
           ,InsertDate
           ,UpdatedBy
           ,UpdatedDate)
     VALUES
           ('{0}'
           ,'UT'
           ,'{1}'
           ,'{2}'
           ,{3}
           ,{4}
           ,'{5}'
           ,'{6}'
           ,getdate()
           ,'{7}'
           ,getdate())", staffNo, reasonCode, date.ToString("yyyy-MM-dd"), fromTime, toTime,
                       totalTime, CommonBusiness.GetCurrentLoginUser(), CommonBusiness.GetCurrentLoginUser()));
                }

                if (sqlList.Count > 0)
                {
                    ut.AddNewUnproductiveTimes(sqlList);

                    MessageBox.Show(this, "Save data successfully.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    this.Close();
                }
                else
                {
                    MessageBox.Show(this, "No data need to be saved.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private DateTime ConvertToDateTime(string hourMinutes)
        {
            int hour = int.Parse(hourMinutes.Split(':')[0]);
            int minute = int.Parse(hourMinutes.Split(':')[1]);

            return new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, hour, minute, 0);
        }

        private void toolStripButtonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void comboBoxTeam_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.BindShiftList();
            this.BindStaffNoList();
            // 重新刷新Grid
            this.BindGrid();
        }

        private void comboBoxShift_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.BindStaffNoList();
            // 重新刷新Grid
            this.BindGrid();
        }

        private void comboBoxStaffNo_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 重新刷新Grid
            this.BindGrid();
        }

        private void FormUnproductiveTimeAdd_Load(object sender, EventArgs e)
        {
            this.BindTeamList();
            this.BindShiftList();
            this.BindStaffNoList();

            this.BindReasonList();
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
        }

        void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            
        }

        private void BindTeamList()
        {
            BusinessBase bb = new BusinessBase();
            DataTable teams = bb.LoadTeamList();

            this.comboBoxTeam.Items.Clear();
            this.comboBoxTeam.Items.Add("");

            foreach (DataRow row in teams.Rows)
            {
                this.comboBoxTeam.Items.Add(row["team"].ToString());
            }

            if (this.comboBoxTeam.Items.Count > 0)
            {
                this.comboBoxTeam.SelectedIndex = 0;
            }

            bb = null;
        }

        private void BindShiftList()
        {
            if (this.comboBoxTeam.Text == "")
            {
                this.comboBoxShift.Items.Clear();
                this.comboBoxShift.Items.Add("");
                return;
            }

            BusinessBase bb = new BusinessBase();
            DataTable shifts = bb.LoadTeamShiftList(this.comboBoxTeam.Text);

            this.comboBoxShift.Items.Clear();
            this.comboBoxShift.Items.Add("");

            foreach (DataRow row in shifts.Rows)
            {
                this.comboBoxShift.Items.Add(row["shift"].ToString());
            }

            if (this.comboBoxShift.Items.Count > 0)
            {
                this.comboBoxShift.SelectedIndex = 0;
            }

            bb = null;
        }

        private void BindStaffNoList()
        {
            if (this.comboBoxTeam.Text == "")
            {
                this.comboBoxStaffNo.Items.Clear();
                this.comboBoxStaffNo.Items.Add("");
                return;
            }

            BusinessBase bb = new BusinessBase();
            DataTable staffs = bb.GetStaffOfTeamShift(this.comboBoxTeam.Text, this.comboBoxShift.Text);

            this.comboBoxStaffNo.BeginUpdate();
            this.comboBoxStaffNo.Items.Clear();
            this.comboBoxStaffNo.Items.Add("");

            foreach (DataRow row in staffs.Rows)
            {
                this.comboBoxStaffNo.Items.Add(row["staffno"].ToString() + "-" + row["name"].ToString());
            }
            if (this.comboBoxStaffNo.Items.Count > 0)
            {
                this.comboBoxStaffNo.SelectedIndex = 0;
            }
            bb = null;

            this.comboBoxStaffNo.EndUpdate();
        }

        private void BindReasonList()
        {
            _valueListReason.ValueListItems.Clear();
            _valueListReason.ValueListItems.Add("", "");

            BusinessBase bb = new BusinessBase();
            DataTable reasons = bb.GetAllReasonList();

            foreach (DataRow row in reasons.Rows)
            {
                if (row["pcode"].ToString() == "16")
                {
                    continue;
                }
                _valueListReason.ValueListItems.Add(row["pcode"].ToString(), row["pcode"].ToString() + "-" + row["pdesc"].ToString());
            }
        }

        private void BindGrid()
        {
            string team = this.comboBoxTeam.Text;
            if (this.comboBoxTeam.Text == "")
            {
                team = "--";
            }

            UnproductiveTime ut = new UnproductiveTime();
            string staffNo = this.comboBoxStaffNo.Text == "" ? "" : this.comboBoxStaffNo.Text.Split('-')[0];

            this.ultraGridMain.DataSource = ut.LoadStaffListForUnproductive(team, this.comboBoxShift.Text, staffNo);
            this.ultraGridMain.DataBind();
        }

        private void ultraGridMain_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            // 自适应列宽
            e.Layout.AutoFitStyle = Infragistics.Win.UltraWinGrid.AutoFitStyle.ResizeAllColumns;
            e.Layout.Override.AllowColSizing = AllowColSizing.Free;
            e.Layout.Override.AllowColMoving = AllowColMoving.NotAllowed;

            // 设置Grid的Split窗口个数，建议设置为1--不允许Split
            e.Layout.MaxColScrollRegions = 1;
            e.Layout.MaxRowScrollRegions = 1;

            // 冻结列
            e.Layout.UseFixedHeaders = false;

            // 排序
            e.Layout.Override.HeaderClickAction = Infragistics.Win.UltraWinGrid.HeaderClickAction.SortSingle;

            // 不允许删除
            e.Layout.Override.AllowDelete = DefaultableBoolean.False;

            // 滚动提示
            e.Layout.Bands[0].ScrollTipField = "StaffNo";

            // 设置编辑模式
            for (int i = 0; i < e.Layout.Bands[0].Columns.Count; i++)
            {
                e.Layout.Bands[0].Columns[i].CellActivation = Activation.NoEdit;
            }

            e.Layout.Bands[0].Columns["Reason"].CellActivation = Activation.AllowEdit;
            e.Layout.Bands[0].Columns["Date"].CellActivation = Activation.AllowEdit;
            e.Layout.Bands[0].Columns["FromTime"].CellActivation = Activation.AllowEdit;
            e.Layout.Bands[0].Columns["ToTime"].CellActivation = Activation.AllowEdit;
            e.Layout.Bands[0].Columns["TotalTime"].CellActivation = Activation.AllowEdit;


            e.Layout.Bands[0].Columns["Date"].CellClickAction = CellClickAction.EditAndSelectText;
            e.Layout.Bands[0].Columns["FromTime"].CellClickAction = CellClickAction.EditAndSelectText;
            e.Layout.Bands[0].Columns["ToTime"].CellClickAction = CellClickAction.EditAndSelectText;
            e.Layout.Bands[0].Columns["TotalTime"].CellClickAction = CellClickAction.EditAndSelectText;

            e.Layout.Bands[0].Columns["Reason"].Header.Appearance.ForeColor = Color.Red;
            e.Layout.Bands[0].Columns["Date"].Header.Appearance.ForeColor = Color.Red;
            //e.Layout.Bands[0].Columns["FromTime"].Header.Appearance.ForeColor = Color.Red;
            //e.Layout.Bands[0].Columns["ToTime"].Header.Appearance.ForeColor = Color.Red;
            e.Layout.Bands[0].Columns["TotalTime"].Header.Appearance.ForeColor = Color.Red;

            e.Layout.Bands[0].Columns["Reason"].ValueList = this._valueListReason;
            e.Layout.Bands[0].Columns["Reason"].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.DropDownList;
        }

        private void ultraGridMain_AfterCellUpdate(object sender, CellEventArgs e)
        {

            this.ultraGridMain.UpdateData();
            if (e.Cell.Column.Key == "FromTime" || e.Cell.Column.Key == "TotalTime")
            {
                try
                {
                    // 按照FromTime和TotalTime计算ToTime，FromTime和ToTime只是参考而已
                    if (string.IsNullOrEmpty(Convert.ToString(e.Cell.Row.Cells["TotalTime"].Value))
                        || string.IsNullOrEmpty(Convert.ToString(e.Cell.Row.Cells["FromTime"].Value)))
                    {
                        return;
                    }

                    int totalTime = int.Parse(Convert.ToString(e.Cell.Row.Cells["TotalTime"].Value));
                    DateTime fromTime = this.ConvertToDateTime(e.Cell.Row.Cells["FromTime"].Text);
                    DateTime toTime = fromTime.AddHours(totalTime);

                    e.Cell.Row.Cells["ToTime"].Value = toTime;
                }
                catch
                {
                    e.Cell.Activate();
                }
            }
            this.ultraGridMain.UpdateData();
        }
    }
}
